package cn.itcast.web.controller.cargo;

import cn.itcast.common.utils.DownloadUtil;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/contract")
public class ExcelController extends BaseController {

	@Reference
	private ContractService contractService;

	//进入下载的页面
	@RequestMapping("/print")
	public String print() {
		return "cargo/print/contract-print";
	}

	/**
	 * 出货表打印
	 *  参数 ：inputDate（船期）
	 *  业务：
	 *      1、根据船期查询数据
	 *      2、构造excel文件
	 *      3、下载excel
	 *   下载的时候，不需要返回值，内部是通过输出流的形式下载文件
	 */
	@RequestMapping("/printExcel")
	public void printExcel(String inputDate) throws IOException {
		//i、根据船期查询数据
		List<ContractProductVo> list = contractService.findByShipTime(inputDate+"%");
		//ii、构造excel文件
		//1.创建工作簿
		Workbook wb = new SXSSFWorkbook();
		//2.创建第一页
		Sheet sheet = wb.createSheet("Sheet1");

		//设置列宽
		sheet.setColumnWidth(1,26 * 256); //设置列宽
		sheet.setColumnWidth(2,12 * 256); //设置列宽
		sheet.setColumnWidth(3,30 * 256); //设置列宽
		sheet.setColumnWidth(4,12 * 256); //设置列宽
		sheet.setColumnWidth(5,15 * 256); //设置列宽
		sheet.setColumnWidth(6,10 * 256); //设置列宽
		sheet.setColumnWidth(7,10 * 256); //设置列宽
		sheet.setColumnWidth(8,26 * 256); //设置列宽
		//合并单元格
		sheet.addMergedRegion(new CellRangeAddress(0,0,1,8)); //合并的区域，行开始，行结束，列开始，列结束


		//3.构造大标题
		//3.1 创建第一行


		Row row = sheet.createRow(0);
		row.setHeightInPoints(36); //设置行高
		//3.2 创建第二个单元格
		Cell cell = row.createCell(1);
		//3.3 设置单元格内容
		//  2020-11--> 2020-11   -->2020年11              月份出货表
		//  2020-01--> 2020-1 -->2020年1
		inputDate = inputDate.replaceAll("-0","-").replaceAll("-","年");
		cell.setCellValue(inputDate + "月份出货表");

		//设置大标题数据样式
		CellStyle style = wb.createCellStyle();  //1.创建一个样式对象
		Font font = wb.createFont();             //2.创建字体对象
		font.setFontName("宋体");                //3.设置字体
		font.setFontHeightInPoints((short)16);   //4.设置字体的大小
		font.setBold(true);//字体加粗            //5.字体加粗
		style.setFont(font);                    //6.设置字体
		style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
		style.setVerticalAlignment(VerticalAlignment.CENTER);

		//设置单元格的样式
		cell.setCellStyle(style);

		//4.构造小标题
		//4.1 创建第二行
		row = sheet.createRow(1);
		row.setHeightInPoints(26); //设置行高
		String [] titles = new String[]{"","客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款" };
		for (int i = 0; i < titles.length; i++) {
			String title = titles[i];
			//4.2 创建每一个单元格
			cell = row.createCell(i);
			//4.3 设置单元格的内容
			cell.setCellValue(title);
			cell.setCellStyle(title(wb));
		}
		//5.循环数据列表，构造数据行内容
		int index = 2;
		for (ContractProductVo cp : list) {
			//for (int i=0;i<5000;i++) {
				row = sheet.createRow(index);
				row.setHeightInPoints(24); //设置行高
				cell = row.createCell(1);
				cell.setCellValue(cp.getCustomName());
				//cell.setCellStyle(text(wb));

				cell = row.createCell(2);
				cell.setCellValue(cp.getContractNo());
				//cell.setCellStyle(text(wb));

				cell = row.createCell(3);
				cell.setCellValue(cp.getProductNo());
				//cell.setCellStyle(text(wb));

				cell = row.createCell(4);
				cell.setCellValue(cp.getCnumber());
				//cell.setCellStyle(text(wb));

				cell = row.createCell(5);
				cell.setCellValue(cp.getFactoryName());

				cell = row.createCell(6);

				String deliveryPeriod = "";
				try {
					deliveryPeriod = new SimpleDateFormat("yyyy-MM-dd").format(cp.getDeliveryPeriod());
				} catch (Exception e) {
				}

				cell.setCellValue(deliveryPeriod); //交期
				//cell.setCellStyle(text(wb));

				cell = row.createCell(7);
				cell.setCellValue(cp.getShipTime());  //船期
				//cell.setCellStyle(text(wb));

				cell = row.createCell(8);
				cell.setCellValue(cp.getTradeTerms()); //
				//cell.setCellStyle(text(wb));

				index++;
			//}
		}
		//iii、文件下载
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		wb.write(bos);
		new DownloadUtil().download(bos,response,"出货表.xlsx"); //ByteArrayOutputStream ,response，下载文件名
	}

	//小标题的样式
	public CellStyle title(Workbook wb){
		CellStyle style = wb.createCellStyle();
		Font font = wb.createFont();
		font.setFontName("黑体");
		font.setFontHeightInPoints((short)12);
		style.setFont(font);
		style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
		style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
		style.setBorderTop(BorderStyle.THIN);						//上细线
		style.setBorderBottom(BorderStyle.THIN);					//下细线
		style.setBorderLeft(BorderStyle.THIN);						//左细线
		style.setBorderRight(BorderStyle.THIN);						//右细线
		return style;
	}

	//文字样式
	public CellStyle text(Workbook wb){
		CellStyle style = wb.createCellStyle();
		Font font = wb.createFont();
		font.setFontName("Times New Roman");
		font.setFontHeightInPoints((short)10);

		style.setFont(font);

		style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
		style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
		style.setBorderTop(BorderStyle.THIN);						//上细线
		style.setBorderBottom(BorderStyle.THIN);					//下细线
		style.setBorderLeft(BorderStyle.THIN);						//左细线
		style.setBorderRight(BorderStyle.THIN);						//右细线

		return style;
	}


	/**
	 * 使用EasyExcel完成excel的生成和下载
	 *  1、数据查询
	 *  2、设置下载信息
	 *  3、调用EasyExcel的工具类完成生成下载
	 */
	@RequestMapping("/printEasyExcel")
	public void printEasyExcel(String inputDate) throws IOException {
		//1、数据查询
		List<ContractProductVo> list = contractService.findByShipTime(inputDate+"%");
		//2、设置下载信息
		response.setContentType("application/vnd.ms-excel"); //下载excel
		response.setCharacterEncoding("utf-8");
		String fileName = URLEncoder.encode("出货表", "UTF-8");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		//3、调用EasyExcel的工具类完成生成下载
		EasyExcel.write(response.getOutputStream())
				.head(ContractProductVo.class) //设置表头
				.sheet("heima127") //指定页名称
				.doWrite(list); //设置数据
	}

	/**
	 * 模板打印
	 *
	 */
	@RequestMapping("/printTemplate")
	public void printTemplate(String inputDate) throws IOException {
		//1.准备数据
		List<ContractProductVo> list = contractService.findByShipTime(inputDate+"%");
		Map map = new HashMap<>();
		inputDate = inputDate.replaceAll("-0","-").replaceAll("-","年");
		map.put("time",inputDate);
		map.put("title1","客户名称");
		//2.设置下载信息
		response.setContentType("application/vnd.ms-excel"); //下载excel
		response.setCharacterEncoding("utf-8");
		String fileName = URLEncoder.encode("出货表", "UTF-8");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		//3.加载excel模板
		String path = session.getServletContext().getRealPath("/")+"/make/tOUTPRODUCT.xlsx";
		//4.创建EasyExcel的excelWtire对象( 用于数据填充)
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
				.head(ContractProductVo.class) //设置表头
				.withTemplate(path) //加载模板
				.build();
		//获取sheet对象
		WriteSheet sheet = EasyExcel.writerSheet().build();
		//5.调用方法完成填充map数据
		excelWriter.fill(map,sheet);
		//6.调用方法完成填充list数据
		excelWriter.fill(list,sheet);
		//7.属性资源，完成下载
		excelWriter.finish(); //下载excel文件，释放内存资源
	}

}
